package com.ciei.dpagm.util;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.signers.JWTSignerUtil;
import java.util.Map;

/**
 * @author wy
 */
public class JwtUtils {

    /**
     * jwt签名器
     */
    private static final String SALT = "6f1wzjkw1^%+&f7o9w@8-@h^6@8xk%7t3t^9t^d%$#9d0=";

    /**
     * jwt 验证
     * @param token  生成的jwt token
     * @return 是否校验通过
     */
    public static JwtVerifyResult validateToken(String token) {
        try {
            JWT jwt = JWT.of(token);
            jwt.setSigner(JWTSignerUtil.hs256(SALT.getBytes()));
            //1.验证hash256签名
            Boolean hs256Bool = jwt.verify();
            if (!hs256Bool) {
                return new JwtVerifyResult(false, "无效的签名");
            }
            JWTPayload jwtPayload = jwt.getPayload();
            //4.将负载参数转换成map返回
            JSONObject payloadJson = jwtPayload.getClaimsJson();
            JwtVerifyResult jwtVerifyResult = new JwtVerifyResult(true, "签名有效");
            jwtVerifyResult.setPayload(JSONUtil.toBean(payloadJson, new TypeReference<Map<String, String>>() {
            }, true));
            return jwtVerifyResult;
        } catch (Exception e) {
            e.printStackTrace();
            return new JwtVerifyResult(false, "无效的签名");
        }
    }
}